<template>
	<view class="form">
		<view class="fromPadding">
			<u--form labelPosition="top" :model="uForm" :rules="rules" ref="uFormRef" labelWidth="150">

				<view class="card">
					<view class="label">
						<text class="title">屋面是否能放置光伏</text>
					</view>
					<view class="itemRow">
						<up-radio-group v-model="uForm.pv" placement="column" @change="groupChange">
							<up-radio :customStyle="{marginBottom: '8px'}" v-for="(item, index) in radiolist1"
								:key="item.id" :label="item.name" :name="item.id" @change="radioChange">
							</up-radio>
						</up-radio-group>
					</view>
				</view>



				<!-- 屋面尺寸 -->
				<view class="card" v-if="uForm.pv == 1">
					<view class="label">
						<text class="title">屋面尺寸</text>
					</view>
					<u-form-item label="长" prop="roof_long" ref="item1">
						<u--input v-model="uForm.roof_long" placeholder="请输入长度" clearable maxlength="6" type="number"
							@input="handleInputChange($event, 'roof_long')"></u--input><text class="unit">mm</text>

					</u-form-item>
					<u-form-item label="宽" prop="roof_width" ref="item1">
						<u--input v-model="uForm.roof_width" placeholder="请输入宽度" clearable maxlength="6" type="number"
							@input="handleInputChange($event, 'roof_width')"></u--input><text class="unit">mm</text>
					</u-form-item>

				</view>



				<view class="card" v-if="uForm.pv == 1">
					<view class="label">
						<text class="title">上传屋面照片</text>
					</view>

					<view class="upload_customRow">
						<view class="uploadCardImg">
							<view class="uploadImg">
								<up-upload :fileList="fileList1" @afterRead="afterRead1" @delete="deletePic1" name="3"
									:previewFullImage="false" :key="fileList1.length" :maxCount="6">
								</up-upload>
							</view>
						</view>
					</view>
				</view>

				<view class="card" v-if="uForm.pv == 0">
					<view class="label">
						<text class="title">上传安装位置照片</text>
					</view>

					<view class="upload_customRow">
						<view class="uploadCardImg">
							<view class="uploadImg">
								<up-upload :fileList="fileList2" @afterRead="afterRead2" @delete="deletePic2" name="3"
									:previewFullImage="false" :key="fileList2.length" :maxCount="6">
								</up-upload>
							</view>
						</view>
					</view>
				</view>

				<view class="desc" v-if="uForm.pv == 0">
					<u-form-item label="描述" prop="desc" type="number" ref="item1" required>
					</u-form-item>
					<up-textarea v-model="uForm.desc" placeholder="请输入描述" clearable :maxCount="200"></up-textarea>
				</view>





			</u--form>
		</view>
		<view class="btn">
			<button @click="submit" type="primary">保存</button>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		onMounted,
		nextTick,
		toRaw
	} from 'vue'
	import {
		onLoad,
		onShow,
		onUnload,
		onReady
	} from "@dcloudio/uni-app";

	import {
		get_oss_url,
		photovoltaic
	} from '@/api/warm.js'

	// 数据
	const uForm = ref({
		pv: 1, //屋面是否能否放置光伏:0=否,1=是  
		roof_long: '', //长
		roof_width: '', //宽
		roof: '', //屋面图片  
		place: '', //安装位置图片  
		desc: '', //描述
	})


	// 基本案列数据
	const radiolist1 = ref([{
			name: '是',
			id: 1,
			disabled: false,
		}, {
			name: '否',
			id: 0,
			disabled: false,
		},


	]);


	// 验证规则
	const rules = {
		roof_long: [{
				required: true,
				message: '请输入长度',
				trigger: ['blur', 'change']
			},
			{
				validator: (rule, value, callback) => {
					if (value && !/^\d+$/.test(value)) {
						return callback(new Error('长度只能输入数字'));
					}
					callback();
				},
				message: '长度只能输入数字',
				trigger: ['blur', 'change']
			}
		],
		roof_width: [{
				required: true,
				message: '请输入宽度',
				trigger: ['blur', 'change']
			},
			{
				validator: (rule, value, callback) => {
					if (value && !/^\d+$/.test(value)) {
						return callback(new Error('宽度只能输入数字'));
					}
					callback();
				},
				message: '宽度只能输入数字',
				trigger: ['blur', 'change']
			}
		],
		desc: [{
			required: true,
			message: '请输入描述',
			trigger: ['blur', 'change']
		}, {
			max: 200,
			message: '描述最多输入200字',
			trigger: ['blur', 'change']
		}]


	}

	// 处理输入的变化，只允许输入数字
	const handleInputChange = (e, field) => {
		let value = e.target.value;
		// 使用正则去掉所有非数字字符
		value = value.replace(/\D/g, ''); // 只保留数字
		// 更新输入的值
		uForm.value[field] = value;
	};


	// 引用
	const uFormRef = ref(null)
	const fileList1 = ref([]); //屋面照片
	const fileList2 = ref([]); //安装照片



	onShow(() => {
		uni.setStorageSync('isUpload', '1'); //清除上传状态
	})

	// 设置规则
	onMounted(() => {
		nextTick(() => {
			if (uFormRef.value) {
				uFormRef.value.setRules(rules)
			}
		})
	})

	// 选择是否能放置光伏
	const groupChange = (n) => {
		console.log('groupChange', n);
		uForm.value.pv = n;
		// 切换时清空用户输入的值和上传的图片
		if (n === 0) {
			uForm.value.desc = ''; // 清空描述
			fileList2.value = []; // 清空安装位置照片
			Imgarr2.value = []
			uForm.value.place = ''

		} else if (n === 1) {
			// 清空屋面尺寸
			uForm.value.roof_long = '';
			uForm.value.roof_width = '';
			fileList1.value = []; // 清空屋面照片
			Imgarr1.value = []
			uForm.value.roof = ''
		}
	};
	// 删除屋面图片
	const deletePic1 = (event) => {
		fileList1.value.splice(event.index, 1);
		// if (!Array.isArray(uForm.value.roof)) {
		// 	uForm.value.roof = []; // 如果不是数组，则初始化为空数组
		// }
		// if (uForm.value.roof.length > event.index) {
		// 	uForm.value.roof.splice(event.index, 1);
		// }

		if (!Array.isArray(Imgarr1.value)) {
			Imgarr1.value = ''; // 如果不是数组，则初始化为空数组
		}
		if (Imgarr1.value.length > event.index) {
			Imgarr1.value.splice(event.index, 1);
		}
		console.log('删除后的图片', Imgarr1.value)


	};

	// 删除安装位置
	const deletePic2 = (event) => {
		fileList2.value.splice(event.index, 1);
		// if (!Array.isArray(uForm.value.place)) {
		// 	uForm.value.place = []; // 如果不是数组，则初始化为空数组
		// }
		// if (uForm.value.place.length > event.index) {
		// 	uForm.value.place.splice(event.index, 1);
		// }

		if (!Array.isArray(Imgarr2.value)) {
			Imgarr2.value = ''; // 如果不是数组，则初始化为空数组
		}
		if (Imgarr2.value.length > event.index) {
			Imgarr2.value.splice(event.index, 1);
		}
		console.log('删除后的图片', Imgarr2.value)



	};




	// 上传屋面位置图片
	const afterRead1 = async (event) => {
		uni.setStorageSync('isUpload', '1')
		const MAX_SIZE = 10 * 1024 * 1024; // 10MB = 10 * 1024 * 1024 字节
		// 检查文件大小是否超过 10MB
		if (event.file.size > MAX_SIZE) {
			uni.showToast({
				title: '文件大小不能超过10MB',
				icon: 'none'
			});
			return;
		}
		let lists = [].concat(event.file);
		let fileListLen = fileList1.value.length;
		// 用来存储上传成功的文件名
		let uploadedFiles = [];
		lists.map((item) => {
			fileList1.value.push({
				...item,
				status: 'uploading',
				message: '上传中',
			});
		});
		for (let i = 0; i < lists.length; i++) {
			const fileName = lists[i].url.match(/[^/]+$/)[0];
			uForm.value.roof = lists[i].url;

			const result = await uploadFilePromise(fileName, lists[i].url, 1);
			let item = fileList1.value[fileListLen];
			fileList1.value.splice(fileListLen, 1, {
				...item,
				status: 'success',
				message: '',
				url: result,
			});
			fileListLen++;
		}
	};

	// 上传安装位置图片
	const afterRead2 = async (event) => {
		uni.setStorageSync('isUpload', '1')
		const MAX_SIZE = 10 * 1024 * 1024; // 10MB = 10 * 1024 * 1024 字节
		// 检查文件大小是否超过 10MB
		if (event.file.size > MAX_SIZE) {
			uni.showToast({
				title: '文件大小不能超过10MB',
				icon: 'none'
			});
			return;
		}
		let lists = [].concat(event.file);
		let fileListLen = fileList2.value.length;
		// 用来存储上传成功的文件名
		let uploadedFiles = [];
		lists.map((item) => {
			fileList2.value.push({
				...item,
				status: 'uploading',
				message: '上传中',
			});
		});
		for (let i = 0; i < lists.length; i++) {
			const fileName = lists[i].url.match(/[^/]+$/)[0];
			uForm.value.place = lists[i].url;
			const path = 'khdImage' + "/" + fileName //处理储存位置
			const result = await uploadFilePromise(path, lists[i].url, 2);
			let item = fileList2.value[fileListLen];
			fileList2.value.splice(fileListLen, 1, {
				...item,
				status: 'success',
				message: '',
				url: result,
			});
			fileListLen++;
		}
	};
	const Imgarr1 = ref([])
	const Imgarr2 = ref([])

	const uploadFilePromise = async (url, fileUrl, type) => {
		const resData = await get_oss_url({
			path: url
		});
		const url1 = resData.data.sign_url //上传图片接口
		wx.getFileSystemManager().readFile({
			filePath: fileUrl, // 文件路径
			encoding: 'base64', // 转换为 base64
			success: function(res) {
				const fileBlob = wx.base64ToArrayBuffer(res.data);
				wx.request({
					url: url1, // 仅为示例，非真实的接口地址
					filePath: url,
					method: 'PUT', // 使用 PUT 方法上传文件
					name: 'file',
					header: {
						"Content-Type": " "
					},
					data: fileBlob, // 上传的文件内容
					success: (res) => {
						if (type == 1) {
							Imgarr1.value.push(resData.data)
							console.log('Imgarr1', Imgarr1.value)
							uni.$u.toast('上传屋面照片成功');
						} else {
							Imgarr2.value.push(resData.data)
							console.log('Imgarr222', Imgarr2.value)
							uni.$u.toast('上传安装位置照片成功');
						}
					},
					fail: function(err) {
						// uni.$u.toast('33333', err);
					},
				})
			},
			fail: function(err) {},
		})

	};

	// 提交方法
	const submit = async () => {
		await nextTick()
		if (!uFormRef.value) return;
		try {
			await uFormRef.value.validate();

			// const fileArr1 = toRaw(fileList1.value)
			uForm.value.roof = Imgarr1.value.map(file => file.full_url).join(',');

			// const fileArr2 = toRaw(fileList2.value)
			uForm.value.place = Imgarr2.value.map(file => file.full_url).join(',');

			if (uForm.value.pv == 1 && Imgarr1.value.length === 0) {
				uni.showToast({
					icon: 'none',
					title: '请至少上传一个屋面图片'
				});
				return;
			}
			if (uForm.value.pv == 0 && Imgarr2.value.length === 0) {
				uni.showToast({
					icon: 'none',
					title: '请至少上传一个安装位置图片'
				});
				return;
			}
			let params = {
				pv: parseInt(uForm.value.pv),
				// roof_long: uForm.value.roof_long,
				// roof_width: uForm.value.roof_width,

				roof_long: uForm.value.roof_long || '',
				roof_width: uForm.value.roof_width || '',
				roof: uForm.value.roof || '',
				desc: uForm.value.desc || '',
				place: uForm.value.place || '',

				// 只有当 pv == 0 时传递 roof
				// ...(uForm.value.pv == 0 && {
				// 	roof: uForm.value.roof || ''
				// }),
				// // 只有当 pv == 1 时传递 place 和 desc
				// ...(uForm.value.pv == 1 && {
				// 	place: uForm.value.place || '',
				// 	desc: uForm.value.desc || ''
				// })
			};
			console.log('提交的参数', params)
			// 提交请求
			const res = await photovoltaic(params)
			if (res.code === 1) {
				uni.showToast({
					icon: 'success',
					title: '提交成功'
				})
				setTimeout(() => {
					uni.navigateTo({
						url: '/pages/common/index'
					})
				}, 50)
			} else {
				uni.showToast({
					icon: 'none',
					title: res.msg
				})
			}
		} catch (err) {
			// uni.showToast({
			// 	icon: 'none',
			// 	title: '请完善内容'
			// })
		}
	}
</script>



<style lang="less" scoped>
	.form {
		padding: 20rpx;
		min-height: 100vh;
		padding-bottom: calc(30rpx + env(safe-area-inset-bottom));
		padding-bottom: calc(30rpx + constant(safe-area-inset-bottom));

		::v-deep .u-form-item {
			.u-form-item__body__right__message {
				text-align: right;
				padding-right: 20rpx;
				padding-bottom: 10rpx;
				box-sizing: border-box;
			}

			.u-form-item__body {
				display: flex;
				flex-direction: row !important;
				padding: 0 !important;
				border-top: 1rpx solid #E0E0E0;
				box-sizing: border-box;

				.u-form-item__body__left {
					height: 90rpx;

					.u-form-item__body__left__content__required {
						left: 0 !important;
					}

					.u-form-item__body__left__content__label {
						padding-left: 20rpx;
					}
				}

				.u-form-item__body__right {
					display: flex;
					align-items: center;
					height: 90rpx;

					.unit {
						display: flex;
						align-items: center;
					}

					.u-form-item__body__right__content__slot {
						display: flex;

						.u-input {
							border: none !important;
						}

						.u-input__content__field-wrapper {
							input {
								text-align: right !important;
							}

							input-placeholde {
								color: red ! !important;
							}
						}

						.checkAddress {
							width: 120rpx;
							display: flex;
							align-items: center;
							font-family: PingFangSC, PingFang SC;
							font-weight: 400;
							font-size: 24rpx;
							color: #CCA05F;
							line-height: 33rpx;
							text-align: left;
							font-style: normal;
						}
					}


				}
			}
		}


		.desc {
			display: flex;
			flex-wrap: wrap;
			background-color: #fff;
			border-radius: 10rpx;
			padding: 0 25rpx 10rpx;
			margin-bottom: 20rpx;
			box-sizing: border-box;

			::v-deep .u-textarea {
				width: 100%;
				// border: none !important;
				margin-bottom: 20rpx;
			}

			::v-deep .u-form-item {
				width: 100%;

				.u-form-item__body {
					border-top: none;

					.u-form-item__body__left {
						height: 90rpx;

						.u-form-item__body__left__content__required {
							left: 0 !important;
						}

						.u-form-item__body__left__content__label {
							padding-left: 20rpx;
						}
					}


				}
			}


		}


		.card {
			background-color: #fff;
			border-radius: 10rpx;
			padding: 0 25rpx 10rpx;
			margin-bottom: 20rpx;
			box-sizing: border-box;

			.label {
				width: 100%;
				height: 90rpx;
				line-height: 90rpx;
				display: flex;
				justify-content: space-between;
				align-items: center;


				.title {
					font-family: PingFangSC, PingFang SC;
					font-weight: 500;
					font-size: 30rpx;
					color: #333333;
					text-align: left;
					font-style: normal;
					position: relative;
					padding-left: 10rpx;
					box-sizing: border-box;

					&::before {
						content: '*';
						position: absolute;
						left: -10rpx;
						top: 3rpx;
						color: red;
					}
				}



			}

			.itemRow {
				display: flex;

				::v-deep .u-radio-group {
					border-top: 1rpx solid #E0E0E0;
					padding-top: 20rpx;
					box-sizing: border-box;
					display: flex;
					flex-direction: row;

					.u-radio {
						width: 150rpx;
					}
				}

				.upload {
					display: flex;
					margin-bottom: 26rpx;
					padding-top: 30rpx;
					border-top: 1rpx solid #E0E0E0;
					box-sizing: border-box;

					.addData {
						flex: 1;
						padding: 0 20rpx;
						box-sizing: border-box;

						.icon {

							image {
								width: 100%;
								height: 230rpx;
							}
						}

						.title {
							font-family: PingFangSC, PingFang SC;
							font-weight: 500;
							font-size: 28rpx;
							color: #333333;
							line-height: 40rpx;
							text-align: left;
							display: block;
							font-style: normal;
							width: 100%;
							height: 68rpx;
							line-height: 68rpx;
							width: 100%;
						}

						.edit {
							width: 100%;
							display: flex;
							justify-content: space-between;

							.copy {
								font-family: PingFangSC, PingFang SC;
								font-weight: 500;
								font-size: 24rpx;
								color: #CCA05F;
								line-height: 33rpx;
								text-align: left;
								font-style: normal;
								padding-bottom: 25rpx;
								box-sizing: border-box;
							}

							.remove {
								font-family: PingFangSC, PingFang SC;
								font-weight: 400;
								font-size: 24rpx;
								color: #F34545;
								line-height: 33rpx;
								text-align: left;
								font-style: normal;
								padding-bottom: 25rpx;
								box-sizing: border-box;

							}
						}


					}


				}
			}

			.upload_customRow {
				display: flex;

				::v-deep .u-form-item {
					width: 100%;
				}

				::v-deep .u-form-item__body {
					display: flex;
					flex-wrap: wrap;
					width: 100% !important;

					.u-form-item__body__left {
						width: 100% !important;
					}

					.u-form-item__body__right {
						display: flex;

					}
				}


				.uploadCardImg {
					width: 100%;
					padding-bottom: 20rpx;
					box-sizing: border-box;

					.uploadImg {
						width: 100%;
						position: relative;
						// overflow: hidden;

						display: flex;
						flex-wrap: wrap;

						::v-deep .u-upload {
							display: flex;
							flex-wrap: wrap;
							min-height: 240rpx;

							.u-upload__button {
								width: 49% !important;
								height: 200rpx !important;
								box-sizing: border-box;
								margin: 0 !important;
							}

							.u-upload__deletable {
								right: 12rpx;
								top: 1rpx;
							}

							.u-upload__success {
								right: 12rpx;
								bottom: 22rpx;
							}

							.u-upload__wrap__preview {
								width: 50%;
								height: 220rpx;
								margin: 0 !important;
								padding: 0 10rpx 20rpx 0 !important;
								border-radius: 10rpx;
								box-sizing: border-box;

								image {
									width: 100% !important;
									height: 100% !important;
									border: 1px solid #E0E0E0;
									background-color: aliceblue;
									border-radius: 10rpx;
									box-shadow: rgba(99, 99, 99, 0.2) 0px 5rpx 10rpx 0rpx;
									box-sizing: border-box;
								}
							}
						}
					}

				}

			}


		}

		.btn {
			width: 100%;
			display: flex;
			justify-content: center;
			padding: 30rpx;
			box-sizing: border-box;
			// position: fixed;
			// left: 0;
			// z-index: 2;
			// bottom: constant(safe-area-inset-bottom);
			// bottom: env(safe-area-inset-bottom);

			button {
				width: 100%;
				height: 88rpx;
				background: linear-gradient(138deg, #EDA55B 0%, #D09A47 100%);
				border-radius: 14rpx;
				font-family: PingFangSC, PingFang SC;
				font-weight: 500;
				font-size: 32rpx;
				color: #FFFFFF;
				line-height: 88rpx;
				font-style: normal;
			}

		}
	}
</style>